package org.edu.service.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.edu.bean.TmBizopen;
import org.edu.common.BaseDao;
import org.edu.service.TmBizopenService;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Service;

/**
 * 
 * @author lzh
 *
 * 2012-4-11
 */
@Service
public class TmBizopenServiceImpl extends BaseDao<TmBizopen> implements TmBizopenService{

	@Override
	public void save(TmBizopen entity) {
		entity.setRegno(getRegNumber());
		super.save(entity);
	}
	public static synchronized String getRegNumber(){
		StringBuilder builder = new StringBuilder("CD");
		builder.append(new SimpleDateFormat("yyyyMMdd").format(new Date()));
		for (int i = 0; i < 3; i++) {
			int num = (int)(Math.random() * 10);
			builder.append(num);
		}
		return builder.toString();
	}
	public TmBizopen findByRegNo(final String regno) {
		return (TmBizopen)hibernateTemplate.execute(new HibernateCallback() {
			public Object doInHibernate(Session ses) throws HibernateException,
					SQLException {
				return ses.createQuery("FROM TmBizopen o WHERE o.regno=?").setParameter(0,regno).uniqueResult();
			}
		});
	}
	@SuppressWarnings("unchecked")
	public List<TmBizopen> findByOpenDate(final Date startdate,final Date enddate) {
		return hibernateTemplate.executeFind(new HibernateCallback() {
			public Object doInHibernate(Session ses) throws HibernateException,
					SQLException {
				return ses.createQuery("FROM TmBizopen o WHERE o.startdate >= ? and o.startdate <= ?")
				.setParameter(0, startdate)
				.setParameter(1, enddate).list();
			}
		});
	}
	public TmBizopen findByCondition(final String condition,final Object where) {
		return (TmBizopen)hibernateTemplate.execute(new HibernateCallback() {
			public Object doInHibernate(Session ses) throws HibernateException,
					SQLException {
				return ses.createQuery("FROM TmBizopen o WHERE "+condition).setParameter(0,where).uniqueResult();
			}
		});
	}
	public TmBizopen findByTaxplayer(final String taxplayer) {
		return (TmBizopen)hibernateTemplate.execute(new HibernateCallback() {
			public Object doInHibernate(Session ses) throws HibernateException,
					SQLException {
				return ses.createQuery("FROM TmBizopen o WHERE o.taxplayer=?").setParameter(0, taxplayer).uniqueResult();
			}
		});
	}
}